<?php

namespace app\service;

use app\model\Goods as GoodsModel;
use think\facade\Db;

class GoodsService
{
    private $goodsModel;
    protected $categoryService;

    public function __construct(){
        $this->goodsModel = app()->make(GoodsModel::class);
        $this->categoryService = app()->make(CategoryService::class);
    }

    /**
     * 保存商品
     *
     * @param $data
     */
    public function save($data) {
        $this->goodsModel->insert($data);
    }
    /**
     * @param array $where
     * @param $order
     * @param int $num
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function queryListByNum($where = array(), $order, $num = 10)
    {
       $object = $this->goodsModel->where($where)->where('coupon_end_time', '>',date('Y-m-d H:i:s'))->order($order)->limit($num)->select();
        //echo $this->goodsModel->getLastSql();exit;
        $list = $object->toArray();
        foreach ($list as $key=>$item) {
            $item['sales'] = $this->handleSales($item['month_sales']);
            $list[$key] = $item;
        }
        return $list;
    }

    /**
     * @param $where
     * @param $order
     * @param int $pageSize
     * @return mixed
     */
    public function queryListByPage($where, $order, $pageSize = 15)
    {
        $object = $this->goodsModel->order('created_time desc')->where($where)->where('coupon_end_time', '>',date('Y-m-d H:i:s'))->paginate($pageSize);
        $list = $object->toArray();
        $list['page'] = $object->render();
        foreach ($list['data'] as $key=>$item) {
            $item['sales'] = $this->handleSales($item['month_sales']);
            $list['data'][$key] = $item;
        }
        return $list;
    }

    /**
     * 根据大淘客商品id查询商品详情
     *
     * @param $dtkGoodsId
     * @return mixed
     */
    public function queryDetailByDtkGoodsId($dtkGoodsId)
    {
        $object = $this->goodsModel->where('dtk_goods_id', $dtkGoodsId)->find();
        if(empty($object)) {
            return null;
        }
        $data = $object->toArray();
        $data['sales'] = $this->handleSales($data['month_sales']);
        $data['special_text'] = explode(',', $data['special_text']);
        return $data;
    }

    /**
     * 处理销量
     *
     * @param $sales
     * @return mixed|string
     */
    public function handleSales($sales): string
    {
        return $sales > 10000 ? ($sales / 10000) .'万' : $sales;
    }
}